package com.example.netty.bio;

import lombok.extern.slf4j.Slf4j;

import javax.sound.midi.Soundbank;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
@Slf4j
public class ServerHandler implements Runnable {
  private   Socket socket;
    public ServerHandler(Socket socket) {
        this.socket=socket;
    }

    @Override
    public void run() {
         //读取缓存数据
        BufferedReader  in =null;
        PrintWriter   out =null;

        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//获取连接中流
            out = new PrintWriter(socket.getOutputStream(),true);
            String expression;
            String result;
            while (true){
                //读到的数据 赋值给 expression

                if ((expression = in.readLine()) == null)
                    break;

                    result = MyProcess.process(expression).toString();
                    out.println(result);

            }

        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getLocalizedMessage());
        }finally {
             if (in!=null) {
                 try {
                     in.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
                 in = null;
             }
            if (out!=null){
                out.close();
                out=null;
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket=null;
            }
    }

    }
}
